$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/advert/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true,hidden:true },
			{ label: '广告名称', name: 'adname', index: 'adName', width: 80 }, 			
			{ label: '广告图片', name: 'adimg', index: 'adimg', width: 80,formatter: function(cellvalue, options, rowdata) {
                    if(rowdata.adimg!=null&&rowdata.adimg!=''){
                        return '<img src='+rowdata.adimg+' width="50" height="50"/>';
                    }else{
                        return '';
                    }

                } },
			{ label: '跳转方式', name: 'type', index: 'type', width: 80,formatter: function(item, index) {
                    if (item === 0) {
                        return '只展示不跳转';
                    }
                    if (item === 1) {
                        return '跳转本小程序';
                    }
                    if (item === 2) {
                        return '公众号文章';
                    }
                } },
            { label: '访问量PV', name: 'pv', index: 'PV', width: 80 },
            { label: '访问数UV', name: 'uv', index: 'UV', width: 80 },
            { label: '点击量', name: 'click', index: 'click', width: 80 },
			{ label: '投放位置', name: 'shelvesposition', index: 'shelvesPosition', width: 80,formatter: function(item, index) {
                    if (item === 0) {
                        return '全部货架';
                    }
                    if (item === 1) {
                        return '部分货架';
                    }
                } },
			{ label: '投放时间', name: 'timestar', index: 'timeStar', width: 80,formatter: function(cellvalue, options, rowdata) {
                    return rowdata.timestar +"<br/>至<br/>"+rowdata.timeend;
                } },

			{ label: '状态', name: 'statu', index: 'statu', width: 80,formatter: function(item, index) {
                    if (item === 0) {
                        return '未开始';
                    }
                    if (item === 1) {
                        return '投放中';
                    }
                    if (item === 1) {
                        return '已结束';
                    }
                } },
            { label: '操作', name: 'sy', width: 70,align:'center',formatter: function(cellvalue, options, rowdata) {
                    return "<a style='cursor:pointer;' onclick='vm.update("+ rowdata.id +")'>" +
                        "编辑</a>&nbsp;&nbsp;" +
                        "<a style='cursor:pointer;' onclick='vm.del("+ rowdata.id +")'>" +
                        "删除</a>";
                }}
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
        fileList1: [],
		q:{
			name:null,
			type:null
		},
        qs:{
            sname:null,
            groupid:null
        },
		showList: true,
		title: null,
		advert: {},
        childShelves:[]
	},
	methods: {
		query: function () {
			vm.reload();
		},
        queryShelves: function () {
            vm.reloadShelves();
        },
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.advert = {};
            vm.advert.type =0;
            vm.advert.shelvesposition = 0;
            $("#bfhj").hide();
            $("#tjsp").hide();
            $("#shelves").html("");
            var temp = "<tr style='height:39px;'>" +
                "<td colspan='4' style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-bottom:solid 1px rgb(226, 229, 237);'>您还未选择货架</td></tr>";
            $("#shelves").append(temp);
            $("#timestar").val("");
            $("#timeend").val("");
		},
        getType: function(){
            if(vm.advert.type == 0){
                $("#lujin").hide();
                $("#lianjie").hide();
            }
            if(vm.advert.type == 1){
                $("#lujin").show();
                $("#lianjie").hide();
            }
            if(vm.advert.type == 2){
                $("#lujin").hide();
                $("#lianjie").show();
            }
        },
        getHj: function(){

            if(vm.advert.shelvesposition == 0){
                $("#bfhj").hide();
                $("#tjsp").hide();
            }
            if(vm.advert.shelvesposition == 1){
                $("#bfhj").show();
                $("#tjsp").show();
            }
        },
        addShelves: function () {
            $("#jqGridAdd").jqGrid({
                url: baseURL + 'sys/goodshelves/listByParams',
                datatype: "json",
                colModel: [
                    { label: 'id', name: 'id', index: 'id', width: 50, key: true,hidden:true },
                    { label: '货架名称', name: 'shelvesname', index: 'shelvesName', width: 170 },
                    { label: '货架地址', name: 'shelvesaddress', index: 'shelvesAddress', width: 225 },
                    { label: '货架分组', name: 'shelvesgroup', index: 'shelvesGroup',width: 170,formatter: function(cellvalue, options, rowdata) {
                            if(rowdata.shelvesgroup!=null&&rowdata.shelvesgroup!=""){
                                var groupname = "";
                                var arr = rowdata.shelvesgroup.split(",");
                                for(var i=0;i<arr.length;i++){
                                    $.ajax({
                                        type: "POST",
                                        async:false,
                                        url: baseURL + "sys/shelvesgroup/info/"+parseInt(arr[i]),
                                        success: function(r){
                                            groupname +=r.shelvesgroup.groupname;
                                            if(i !=arr.length-1){
                                                groupname +="/";
                                            }

                                        }
                                    });
                                }
                                return groupname;
                            }else{
                                return '未分组';
                            }


                        } }
                ],
                viewrecords: true,
                height: 385,
                rowNum: 10,
                rowList : [10,30,50],
                rownumbers: true,
                rownumWidth: 25,
                autowidth:true,
                multiselect: true,
                pager: "#jqGridPagerAdd",
                jsonReader : {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames : {
                    page:"page",
                    rows:"limit",
                    order: "order"
                },
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    $("#jqGridPagerAdd").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                }
            });
            vm.queryGroup();
            $('#myModal').modal();
        },
        showShelves:function () {
            var grid = $("#jqGridAdd");
            var rowKey = grid.getGridParam("selrow");
            if(!rowKey){
                alert("请选择一条记录");
                return ;
            }
            var rows = grid.getGridParam("selarrrow");

            var temp = "";
            $("#shelves").html("");

            for(var i=0;i<rows.length;i++){
                var obj = {};
                var isExits = false;
                if(vm.childShelves.length>0){
                    for(var j=0;j<vm.childShelves.length;j++){
                        if(rows[i]==vm.childShelves[j].id){
                            isExits = true;
                        }
                    }
                    if(!isExits){
                        obj.id = rows[i];
                        obj.name = grid.getRowData(rows[i]).shelvesname;
                        obj.address = grid.getRowData(rows[i]).shelvesaddress;
                        obj.group = grid.getRowData(rows[i]).shelvesgroup;
                        vm.childShelves.push(obj);
                    }

                }else{
                    obj.id = rows[i];
                    obj.name = grid.getRowData(rows[i]).shelvesname;
                    obj.address = grid.getRowData(rows[i]).shelvesaddress;
                    obj.group = grid.getRowData(rows[i]).shelvesgroup;
                    vm.childShelves.push(obj);
                }

            }

            for(var k=0;k<vm.childShelves.length;k++){
                temp +="<tr style='height:39px;' ><td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'>"+vm.childShelves[k].name+"</td>" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.childShelves[k].address+"</td>" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.childShelves[k].group+"</td>" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>" +
                    "<img src='../../statics/img/ico16-delete.png' onclick='vm.removeShelves("+vm.childShelves[k].id+")' style='cursor: pointer'></td></tr>";


            }
            $("#shelves").html(temp);

            $('#myModal').modal("hide");

        },
        removeShelves: function (id) {
            var temp = "";
            if(vm.childShelves.length==1 && vm.childShelves.length>0){
                alert("至少选择一个货架");
                return;
            }
            $("#shelves").html("");
            var childShelvestemp = [];
            for(var i=0;i<vm.childShelves.length;i++){
                var obj = {};

                if(vm.childShelves[i].id !=id){
                    obj.id = vm.childShelves[i].id;
                    obj.name = vm.childShelves[i].name;
                    obj.address = vm.childShelves[i].address;
                    obj.group = vm.childShelves[i].group;
                    childShelvestemp.push(obj);


                    temp +="<tr style='height:39px;' ><td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'>"+vm.childShelves[i].name+"</td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.childShelves[i].address+"</td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.childShelves[i].group+"</td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>" +
                        "<img src='../../statics/img/ico16-delete.png' onclick='vm.removeShelves("+vm.childShelves[i].id+")' style='cursor: pointer'></td></tr>";

                }

            }
            vm.childShelves = childShelvestemp;
            $("#shelves").append(temp);
        },
		update: function (id) {

			vm.showList = false;
            vm.title = "修改";

            vm.childShelves = [];
            vm.getInfo(id);
            vm.getType();
            $("#timestar").val(vm.advert.timestar);
            $("#timeend").val(vm.advert.timeend);
            if(vm.advert.shelvesposition == 1){
                var shelvesids = vm.advert.shelvesid.split(",");
                var temp = "";
                for(var i=0;i<shelvesids.length;i++){
                    var obj = {};
                    $.ajax({
                        type: "POST",
                        async:false,
                        url: baseURL + "sys/goodshelves/info/"+shelvesids[i],
                        success: function(r){
                            obj.id = r.goodshelves.id;
                            obj.name = r.goodshelves.shelvesname;
                            obj.address = r.goodshelves.shelvesaddress;
                            var groupname = "";
                            if(r.goodshelves.shelvesgroup!=null&&r.goodshelves.shelvesgroup!=""){
                                var arr = r.goodshelves.shelvesgroup.split(",");
                                for(var i=0;i<arr.length;i++){
                                    $.ajax({
                                        type: "POST",
                                        async:false,
                                        url: baseURL + "sys/shelvesgroup/info/"+parseInt(arr[i]),
                                        success: function(r){
                                            groupname +=r.shelvesgroup.groupname;
                                            if(i !=arr.length-1){
                                                groupname +="/";
                                            }

                                        }
                                    });
                                }
                            }else{
                                groupname =  '未分组';
                            }
                            obj.group = groupname;
                            vm.childShelves.push(obj);

                        }
                    });
                }

                $("#shelves").html("");
                for(var k=0;k<vm.childShelves.length;k++){
                    temp +="<tr style='height:39px;' ><td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'>"+vm.childShelves[k].name+"</td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.childShelves[k].address+"</td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.childShelves[k].group+"</td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>" +
                        "<img src='../../statics/img/ico16-delete.png' onclick='vm.removeShelves("+vm.childShelves[k].id+")' style='cursor: pointer'></td></tr>";


                }
                $("#shelves").html(temp);
                $("#bfhj").show();
                $("#tjsp").show();

            }
		},
		saveOrUpdate: function (event) {
			var url = vm.advert.id == null ? "sys/advert/save" : "sys/advert/update";
			vm.advert.timestar = $("#timestar").val();
            vm.advert.timeend = $("#timeend").val();
            var st = new Date(vm.advert.timestar).getTime();
            var et = new Date(vm.advert.timeend).getTime();

            if(vm.advert.adname == ''|| typeof vm.advert.adname == 'undefined'){
                alert("广告名称不能为空");
            }else if(vm.fileList1.length ==0){
                alert("广告图片不能为空");
            }else if(vm.advert.shelvesposition == 1&&vm.childShelves.length==0){
                alert("货架不能为空");
            }else if(vm.advert.timestar == ""&&vm.advert.timeend==""){
                alert("投放时间不能为空");
            }else if((vm.advert.timestar == ""&&vm.advert.timeend!="")||(vm.advert.timestar != ""&&vm.advert.timeend=="")){
                alert("请补充完整该广告的投放时间");
            }else if(st>et){
                alert("开始时间不能大于结束时间");
            }else{
                vm.advert.shelvesid = "";
                for(var i=0;i<vm.childShelves.length;i++){
                    vm.advert.shelvesid += vm.childShelves[i].id;
                    if(i!=vm.childShelves.length-1){
                        vm.advert.shelvesid += ",";
                    }
                }
                vm.advert.adimg = '';
                if(vm.fileList1.length>0){
                    vm.advert.adimg = vm.fileList1[0].url;
                }
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.advert),
                    success: function(r){
                        if(r.code === 0){
                            alert('操作成功', function(index){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            }

		},
		del: function (id) {
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sys/advert/delete/"+id,
                    contentType: "application/json",
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
        handleRemove1: function(file, fileList) {
            console.log(fileList);
            if(fileList.length>0){
                vm.fileList1 = [];
                for(var i=0;i<fileList.length;i++){
                    vm.fileList1.push({name: fileList[i].name,url: fileList[i].url});

                }
            }
            console.log(vm.fileList1);

        },
        handlePreview: function(file) {
            console.log(file);
        },

        handsuccess1: function(response, file, fileList) {
            vm.fileList1.push({name: response.url,url: response.url});

        },
		getInfo: function(id){
            $.ajax({
                type: "POST",
                async:false,
                url: baseURL + "sys/advert/info/"+id,
                success: function(r){
                    vm.advert = r.advert;
                    vm.fileList1 = [];
                    if(r.advert.adimg!=null&&r.advert.adimg!=''){
                        vm.fileList1.push({name: r.advert.adimg,url: r.advert.adimg});
                    }

                }
            });
		},
        queryGroup: function(){
            $("#s_id").html("");
            $.get(baseURL + "sys/shelvesgroup/alllist", function(r){
                var temp = "<option value=''></option><option value='0'>未分组</option>";
                $.each(r.alllist, function (i) {

                    temp +="<option value='"+r.alllist[i].id+"'>"+r.alllist[i].groupname+"</option>";

                });
                $("#s_id").append(temp);

            });
        },
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{'name':vm.q.name,'type':vm.q.type},
                page:page
            }).trigger("reloadGrid");
		},
        reloadShelves: function (event) {
            var page = $("#jqGridAdd").jqGrid('getGridParam','page');
            $("#jqGridAdd").jqGrid('setGridParam',{
                postData:{'sname':vm.qs.sname,'groupid':vm.qs.groupid},
                page:page
            }).trigger("reloadGrid");
        },
	}
});